import React, {Component} from 'react';
import {FlatList, View} from 'react-native';
import SessionListItem from "./item/SessionListItem";
import {globalStore} from "../../libs/ShareStore";
import {listViewStyle} from "./style/listViewStyle";
import SessionListData from "../../model/item/SessionListData";
import HistorySessionDTO from "../../libs/sdk/echatim/model/dto/HistorySessionDTO";


type SessionListStateType = {
    items:Array<SessionListData>,
    refreshing:boolean,
}

export default class SessionListView extends Component<any, SessionListStateType> {
    constructor(props) {
        super(props);

        this.state = {
            items:new Array<SessionListData>(),
            refreshing: false
        };
        globalStore.addSessionListener(this.onSessionUpdate.bind(this));
    }

    componentDidMount(): void {
        this.onSessionUpdate(globalStore.sessionList);
    }


    onSessionUpdate(sessions:Array<HistorySessionDTO>):void{
        this.setState( {
            items:sessions.map((v)=>{
                const data =  new SessionListData();
                data.id = v.toTarget + '';
                data.avatar = v.toTargetAvatar;
                data.name = v.toTargetName;
                data.body = v.body.body;
                data.unread = v.unread;
                data.createTime = v.createTime;

                return data;
            }),
            refreshing: !this.state.refreshing
        });
    }

    render() {
        return (
            <View style = {listViewStyle.container}>
                <View style={listViewStyle.list}>
                    <FlatList
                        extraData = {this.state.refreshing}
                        data = {this.state.items}
                        renderItem = {({item})=><SessionListItem data={item}  avatar={item.avatar}  body={item.body} name={item.name}  unread={item.unread}/>}
                    />
                </View>
            </View>
        );
    }
}

